package cn.xjt.screenShare.netty;

import cn.xjt.screenShare.constant.EnumConstant;
import cn.xjt.screenShare.netty.decoder.ImageDecoder;
import cn.xjt.screenShare.netty.share.CaptureImage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class NettyClient{
	private Bootstrap bootstrap = new Bootstrap();
	private static NettyClient client;

	public static NettyClient getInstance() {
		if (client == null)
			client = new NettyClient();
		return client;
	}

	public boolean connectServer(String address){
		try {
			if (address == null || address.equals(""))
				address = "localhost";
			bootstrap.connect(new InetSocketAddress(address, EnumConstant.Port.SERVER.port)).sync().channel();
		} catch (Exception e) {
			System.err.println("Can't connect to remote screen server...");
			return false;
		}
		return true;
	}

	public static void main(String[] args) throws InterruptedException {
		Bootstrap handler = new Bootstrap()
				.group(new NioEventLoopGroup())
				.channel(NioSocketChannel.class)
				.handler(new ChannelInitializer<NioSocketChannel>() {
					@Override
					protected void initChannel(NioSocketChannel ch){
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast(new ImageDecoder());
						pipeline.addLast(new ChannelInboundHandlerAdapter(){
							@Override
							public void channelRead(ChannelHandlerContext ctx, Object msg) {
//								接受到图片数据
								CaptureImage captureImage = (CaptureImage) msg;
							}
						});
					}
				});
		Channel channel = handler.connect(new InetSocketAddress("localhost", 8888))
				.sync().channel();
	}

}
